package handler

import (
	"github.com/gin-gonic/gin"
	"house/api/request"
	"house/api/resp"
	"house/internal/dao"
	"house/internal/model"
	"time"
)

func AddReservation(c *gin.Context) {
	var req request.AddReservation
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "验证失败", err.Error())
		return
	}
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if user.TypeUser != 1 {
		resp.Error(c, 100000, "需买家权限", false)
		return
	}

	var house model.House
	dao.GetOneById(req.HouseId, &house)
	if house.Id == 0 {
		resp.Error(c, 100000, "该房源未存在", false)
		return
	}
	parseTime, _ := time.Parse(time.DateTime, req.ReservationTime)

	if time.Now().Unix() > parseTime.Unix() {
		resp.Error(c, 100000, "预约时间小于当前时间", false)
		return
	}
	result := dao.Create(&model.Reservation{
		UserId:          c.GetUint("userId"),
		HouseId:         req.HouseId,
		ReservationTime: parseTime,
	})
	if !result {
		resp.Error(c, 100000, "预约失败", false)
		return
	}
	resp.Success(c, "预约成功", true)
}

func DeleteReservation(c *gin.Context) {
	var req request.DeleteReservation
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "验证失败", err.Error())
		return
	}
	var reservation model.Reservation
	dao.GetOneById(req.Id, &reservation)
	if reservation.Id == 0 {
		resp.Error(c, 100000, "该预约信息不存在", false)
		return
	}
	result := dao.Delete(&model.Reservation{
		Id: req.Id,
	})
	if !result {
		resp.Error(c, 100000, "取消预约失败", false)
		return
	}
	resp.Success(c, "取消预约成功", true)

}
